package com.example.forum.controller;

import com.google.code.kaptcha.Producer;
import com.jhlabs.image.ImageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class KaptchaController {
    public static final Logger logger= LoggerFactory.getLogger(KaptchaController.class);
    @Autowired
    private Producer kaptchaProducer;

    @RequestMapping("/kaptchaProducer")
    public void kaptchaProducer(HttpServletResponse response, HttpSession session){
        //设置服务器返回数据的格式
        response.setContentType("image/png");
        //生成随机字符
        String text = kaptchaProducer.createText();
        //用随机字符来生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(text);
        //将图片输出给浏览器
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
            //将验证码保存到session中
            session.setAttribute("checkCode",text);
        } catch (IOException e) {
            logger.error("验证码响应出错:"+e.getMessage());
        }
    }
}
